# == Schema Information
# Schema version: 38
#
# Table name: visiteds
#
#  id         :integer(11)     not null, primary key
#  user_id    :integer(11)
#  school_id  :integer(11)
#  visit_at   :date
#  created_at :datetime
#

class Visited < ActiveRecord::Base
  belongs_to :traveler, :class_name => "User", :foreign_key => "user_id"
  belongs_to :school
  
  def self.all
    self.find(:all,
              :limit   => 10, 
              :order   => "visiteds.visit_at desc", 
              :include => [:school, :traveler])
  end

  def self.archives
    date_func = "extract(year from created_at) as year,extract(month from created_at) as month"
    
    counts = Visited.find_by_sql(["select count(*) as count, #{date_func} from visiteds where created_at < ? group by year,month order by year asc,month asc",Time.now])
    
    sum = 0
    result = counts.map do |entry|
      sum += entry.count.to_i
      {
        :name => entry.year + "年" + entry.month + "月",
        :month => entry.month.to_i,
        :year => entry.year.to_i,
        :delta => entry.count,
        :sum => sum
      }
    end
    return result.reverse
  end
end
